<!-- 登录账号手机号输入组件 -->
<script lang="ts" setup>
import { ListenerProp } from "@varlet/ui";
import { ref, watchEffect } from "vue";

import { isPhone, isEmail, isPhoneAndEmail } from "/@/utils/";

import InputBase from "../form/InputBase.vue";
import { i18nTranslate } from "/@/i18n";
type SignInType = 'email' | 'phone';

// 定义 props
const props = defineProps<{
    modelValue?: string;
    autofocus?: boolean;
    // 地区码
    areacode: string;
    onChange?: ListenerProp<(value: string) => void>
}>();

const type = ref(<SignInType>'email');

// 定义外部事件
const emit = defineEmits(["update:modelValue", 'change', 'change-type']);

// 内部事件
const onClear = () => emit('update:modelValue', '');
const onInput = (value: string) => {
    // 判断文本类型

    emit('update:modelValue', value);
};
const onChangeCode = (code: string) => {
    console.log('onChangeCode', code);
    emit('change', code)
};

// 校验规则，返回true表示通过校验
const rules = [
    (v: string) => !!v || i18nTranslate('input_account_empty'),
    (v: string) => type.value === 'phone' ? isPhone(v) || i18nTranslate('form_phone_not_correct') : true,
    (v: string) => type.value === 'email' ? isEmail(v) || i18nTranslate('form_email_not_correct') : true,
];

watchEffect(() => {
    if (props.modelValue && isPhoneAndEmail(props.modelValue)) {
        type.value = 'phone'
        emit('change-type', 'phone');
    } else {
        type.value = 'email'
        emit('change-type', 'email');
    }
});

</script>
<template>
    <InputBase :label="$t('signin_account_title')" clearable :maxlength="200" type="text" :model-value="modelValue"
        :rules="rules" :autofocus="autofocus" @clear="onClear" @input="onInput">
        <template #prepend>
            <div v-show="type === 'phone'">
                <AreaCodePicker :model-value="areacode" @change="onChangeCode"></AreaCodePicker>
            </div>
        </template>
    </InputBase>
</template>
<style lang="scss" scoped></style>
